const template = `
<div class="edit-box" v-bind="$attrs">
    <div class="tools">
        <div class="group" v-for="group,groupIndex in toorBarOptions" :key="groupIndex">
            <button
                name="tool"
                :class="{
                    'has-tip': !tool.options,
                    active: tool.check && cursorPositionStyle.includes(tool.check)
                }"
                v-for="tool in group"
                :key="tool.name"
                :tip="tool.name"
                @click="setFormat(tool)"
            >
                <span class="iconfont" :class="tool.icon"></span>
                <ul class="menu-sub" v-if="tool.options">
                    <li
                        v-for="(subtool, index) in tool.options"
                        :key="index"
                        @click="setFormat(subtool, true)"
                        ><span class="iconfont" :class="subtool.icon"></span> {{ subtool.name }}</li
                    >
                </ul>
            </button>
        </div>
    </div>

    <div
        :contenteditable="options && !options.readOnly"
        id="edit"
        ref="editRef"
        :placeholder="options && options.placeholder"
        @input="onInput"
        @click="onClick"
    ></div>
</div>
`;

const RichEditor = {
  template,
  props: {
    // TODO: 待补充代码 目标 1
    value: {
      required: true,
      type: String,
      default: false,
    },
    options: {
      required: true,
      type: Object,
      default: {
        toolbar: [],
        placeholder: "Insert text here ...",
        readOnly: false,
      },
      validator(option) {
        if (option != "[object Object]")
          throw new Error("options参数格式错误！");
        if (!Array.isArray(option["toolbar"]))
          throw new Error("options参数的toolbar 配置错误！");
      },
    },
    // TODO: END
  },
  emits: ["update:value"],
  setup(props, ctx) {
    const editRef = ref(null);

    //最终生成的toolbar配置项
    const toorBarOptions = ref([]);

    onMounted(() => {
      editRef.value.innerHTML = props.value || "";
      toorBarOptions.value = formatOptions(props.options?.toolbar);
    });

    function formatOptions(toolbar) {
      if (!toolbar || toolbar.length == 0) return defaultToolBar;
      // TODO: 待补充代码 目标 2
      let str = JSON.stringify(toolbar);
      let test = "";
      for (let i = 0, left = false; i < str.length; i++) {
        if (str[i] == ":") left = true;
        if (left) {
          if (str[i] == "]") left = false;
        } else test += str[i];
      }
      str = test;
      for (const key in toolsMap) {
        if (!toolsMap[key].childrens) {
          str = str.replaceAll(/,"(\w+)",/g, `,["$1"],`);
          str = str.replaceAll(`"${key}"`, JSON.stringify(toolsMap[key]));
        } else {
          str = str.replaceAll(
            `[{"${key}"}]`,
            `{"${key}": ${JSON.stringify(toolsMap[key])}}`
          );
          str = str.replaceAll("childrens", "options");
        }
      }
      str = JSON.parse(str);
      console.log(str);
      return str;
      // TODO: END
    }

    //在第一次输入时获取下光标位置样式，后续不获取
    const watchInput = ref(true);
    const onInput = (e) => {
      ctx.emit("update:value", e.target.innerHTML);
      watchInput.value && getActiveStatus();
      watchInput.value = false;
    };

    const watchClick = ref(true);
    const onClick = (e) => {
      watchClick.value && getActiveStatus();
      watchClick.value = true;
    };

    //点击可编辑区域，获取光标位置激活的样式
    const cursorPositionStyle = ref([]);
    //获取光标处激活的工具
    function getActiveStatus() {
      cursorPositionStyle.value = [];
      // 获取Selection对象
      var selection = window.getSelection();
      function getAllTagName(node) {
        if (node.id === "edit" || !node) return;
        const tagName = node.tagName;
        !cursorPositionStyle.value.includes(tagName) &&
          cursorPositionStyle.value.push(tagName);
        node.size && cursorPositionStyle.value.push("size");
        node.face && cursorPositionStyle.value.push("face");
        node.color && cursorPositionStyle.value.push("color");
        node.style &&
          node.style.backgroundColor &&
          cursorPositionStyle.value.push("background-color");
        node.parentNode && getAllTagName(node.parentNode);
      }
      getAllTagName(selection.anchorNode.parentNode);
    }
    //isSub 是否是选择器里的二级控件
    function setFormat(tool, isSub = false) {
      if (tool.options) return;
      watchClick.value = false;
      var selection = window.getSelection();
      //如果当前光标有聚焦，并且可以在光标后沿用设置的格式
      if (selection.focusNode && !tool.onlySelection) {
        //如果没有选区，则打开/关闭此工具
        cursorPositionStyle.value.includes(tool.check)
          ? cursorPositionStyle.value.splice(
              cursorPositionStyle.value.indexOf(tool.check),
              1
            )
          : cursorPositionStyle.value.push(tool.check);
      }

      const aCommandValue =
        isSub || ["insertimage", "createlink"].includes(tool.aCommandName)
          ? tool.aCommandValue
          : cursorPositionStyle.value.includes(tool.check)
          ? ""
          : tool.aCommandValue || "";
      //非二级控件点击后要取消状态, 图片、链接
      document.execCommand(tool.aCommandName, false, aCommandValue);
    }

    return {
      editRef,
      toorBarOptions,
      onInput,
      onClick,
      cursorPositionStyle,
      setFormat,
    };
  },
};
